package com.fh.shop.consumer;

import com.alibaba.fastjson.JSON;
import com.fh.shop.util.MailUtil;
import com.fh.shop.config.MQConstant;
import com.fh.shop.message.MailMessage;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class MailConsumer {
    @Autowired
    private MailUtil mailUtil;

    //消费者处理队列
    @RabbitListener(queues = MQConstant.mailDirect.QUEUE)
    public void mailConsumer(String msg, Message message, Channel channel) throws IOException {
        //标志
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            MailMessage mail = JSON.parseObject(msg, MailMessage.class);
            mailUtil.sendMail(mail.getTo(),mail.getTitle(),mail.getContent());
        } catch (Exception e) {
            e.printStackTrace();
            //记录异常数据
            log.error("发送邮件{}异常,异常信息:{}",msg,e.getMessage());
        } finally {
            //都会响应给mq
            channel.basicAck(deliveryTag,false);
        }
    }
}
